<template>
	<view class="container">
		<view class="form">
			<view class="form-item">
				<text class="label">脚本名称</text>
				<input class="input" v-model="formData.name" placeholder="请输入脚本名称" />
			</view>
			
			<view class="form-item">
				<text class="label">脚本描述</text>
				<input class="input" v-model="formData.description" placeholder="请输入脚本描述（可选）" />
			</view>
			
			<view class="form-item">
				<text class="label">脚本内容</text>
				<!-- #ifdef H5 -->
				<div
					ref="scriptEditor"
					class="script-input" 
					contenteditable="true"
					@input="handleScriptInput"
					:data-placeholder="placeholder"
				></div>
				<!-- #endif -->
				
				<!-- #ifndef H5 -->
				<textarea ref="scriptTextarea" class="script-input" :value="formData.content" @input="handleScriptInput" placeholder="请输入JavaScript脚本..." maxlength="10000"></textarea>
				<!-- #endif -->

				<view class="script-desc">
					<text>脚本将接收一个文件信息数组 `files` 作为输入，每个文件包含路径和元数据，需返回一个处理后的对象数组。</text>
					<text>示例: return files.map(file => ({ '文件名': file.path, '时长': file.metadata.duration }));</text>
				</view>
			</view>
			
			<view class="form-item">
				<text class="label">预设模板</text>
				<picker @change="bindTemplateChange" :value="templateIndex" :range="templates" range-key="name">
					<view class="picker">
						选择模板：{{ templates[templateIndex].name }}
					</view>
				</picker>
			</view>
		</view>
		
		<view class="footer">
			<button class="submit-btn" @click="handleSubmit">{{ isEdit ? '更新脚本' : '创建脚本' }}</button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			formData: {
				name: '',
				description: '',
				content: ''
			},
			isEdit: false,
			editId: null,
			placeholder: '请输入JavaScript脚本...',
			templateIndex: 0,
			templates: [
				{
					name: '请选择模板',
					content: ''
				},
				{
					name: '基础文件信息提取',
					content: `// 基础文件信息提取模板
return files.map(file => {
	const parts = file.path.split('/');
	const fileName = parts[parts.length - 1];
	const duration = file.metadata.duration || 0;
	const size = file.metadata.size || 0;
	
	return {
		'文件路径': file.path,
		'文件名': fileName,
		'时长(秒)': Math.round(duration),
		'文件大小(MB)': Math.round(size / 1024 / 1024 * 100) / 100
	};
});`
				},
				{
					name: '视频文件详细信息',
					content: `// 视频文件详细信息提取模板
return files.map(file => {
	const parts = file.path.split('/');
	const fileName = parts[parts.length - 1];
	const duration = file.metadata.duration || 0;
	const size = file.metadata.size || 0;
	const width = file.metadata.width || 0;
	const height = file.metadata.height || 0;
	
	// 格式化时长为 HH:MM:SS
	const hours = Math.floor(duration / 3600);
	const minutes = Math.floor((duration % 3600) / 60);
	const seconds = Math.floor(duration % 60);
	const formatDuration = \`\${hours.toString().padStart(2, '0')}:\${minutes.toString().padStart(2, '0')}:\${seconds.toString().padStart(2, '0')}\`;
	
	return {
		'文件名': fileName,
		'文件路径': file.path,
		'时长': formatDuration,
		'分辨率': width && height ? \`\${width}x\${height}\` : '未知',
		'文件大小(MB)': Math.round(size / 1024 / 1024 * 100) / 100,
		'视频格式': file.metadata.mimeType || '未知'
	};
});`
				},
				{
					name: '目录层级解析',
					content: `// 目录层级解析模板
return files.map(file => {
	const parts = file.path.split('/');
	const fileName = parts[parts.length - 1];
	const parentDir = parts.length > 1 ? parts[parts.length - 2] : '';
	const duration = file.metadata.duration || 0;
	
	return {
		'文件名': fileName,
		'父目录': parentDir,
		'完整路径': file.path,
		'时长(秒)': Math.round(duration),
		'层级深度': parts.length
	};
});`
				}
			]
		}
	},
	onLoad(options) {
		if (options.id) {
			this.isEdit = true;
			this.editId = options.id;
			this.loadScriptData(options.id);
		} else {
			// 新建脚本时使用默认模板
			this.formData.content = this.templates[1].content;
		}
	},
	mounted() {
		// #ifdef H5
		// 初始化 contenteditable div 的内容
		if (this.$refs.scriptEditor) {
			this.$refs.scriptEditor.innerText = this.formData.content;
		}
		// #endif
	},
	methods: {
		loadScriptData(id) {
			const scriptList = uni.getStorageSync('scriptList') || [];
			const script = scriptList.find(item => item.id === id);
			if (script) {
				this.formData = {
					name: script.name,
					description: script.description || '',
					content: script.content
				};
			}
		},
		bindTemplateChange(e) {
			this.templateIndex = e.detail.value;
			if (this.templateIndex > 0) {
				this.formData.content = this.templates[this.templateIndex].content;
				// #ifdef H5
				if (this.$refs.scriptEditor) {
					this.$refs.scriptEditor.innerText = this.formData.content;
				}
				// #endif
			}
		},
		handleScriptInput(event) {
			// #ifdef H5
			this.formData.content = event.target.innerText;
			// #endif

			// #ifndef H5
			this.formData.content = event.detail.value;
			// #endif
		},
		handleSubmit() {
			if (!this.formData.name.trim()) {
				uni.showToast({
					title: '请输入脚本名称',
					icon: 'none'
				});
				return;
			}
			
			if (!this.formData.content.trim()) {
				uni.showToast({
					title: '请输入脚本内容',
					icon: 'none'
				});
				return;
			}
			
			const scriptList = uni.getStorageSync('scriptList') || [];
			
			if (this.isEdit) {
				// 编辑模式
				const targetIndex = scriptList.findIndex(item => item.id === this.editId);
				if (targetIndex !== -1) {
					scriptList[targetIndex] = {
						...scriptList[targetIndex],
						name: this.formData.name,
						description: this.formData.description,
						content: this.formData.content,
						updateTime: new Date().toLocaleString()
					};
				}
			} else {
				// 新建模式
				const newScript = {
					id: Date.now().toString(),
					name: this.formData.name,
					description: this.formData.description,
					content: this.formData.content,
					createTime: new Date().toLocaleString()
				};
				scriptList.push(newScript);
			}
			
			uni.setStorageSync('scriptList', scriptList);
			
			uni.showToast({
				title: this.isEdit ? '更新成功' : '创建成功',
				icon: 'success',
				success: () => {
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				}
			});
		}
	}
}
</script>

<style>
.container {
	padding: 20px;
	min-height: 100vh;
	background-color: #f8f8f8;
	display: flex;
	flex-direction: column;
}

.form {
	flex: 1;
}

.form-item {
	background: #fff;
	border-radius: 12px;
	padding: 15px;
	margin-bottom: 20px;
}

.label {
	font-size: 14px;
	color: #333;
	margin-bottom: 10px;
	display: block;
}

.input {
	width: 100%;
	height: 40px;
	border: 1px solid #ddd;
	border-radius: 8px;
	padding: 0 12px;
	font-size: 14px;
}

.picker {
	width: 100%;
	height: 40px;
	line-height: 40px;
	border: 1px solid #ddd;
	border-radius: 8px;
	padding: 0 12px;
	font-size: 14px;
	background-color: #f8f9fa;
}

.script-input {
	width: 100%;
	min-height: 200px;
	border: 1px solid #ddd;
	border-radius: 8px;
	padding: 12px;
	font-size: 14px;
	font-family: monospace;
	box-sizing: border-box;
	/* #ifdef H5 */
	white-space: pre-wrap;
	word-wrap: break-word;
	/* #endif */
}

/* #ifdef H5 */
.script-input:empty:before {
  content: attr(data-placeholder);
  color: #999;
}
/* #endif */

.script-desc {
	font-size: 12px;
	color: #999;
	margin-top: 10px;
	display: flex;
	flex-direction: column;
}

.footer {
	padding: 20px 0;
}

.submit-btn {
	background-color: #007AFF;
	color: #fff;
	border-radius: 8px;
	font-size: 16px;
}
</style> 